<template>
  <view class="container">
    <text>上传.mp4格式的视频，20MB以内</text>
    <uni-file-picker v-model="tempFile" limit="1" file-extname="mp4" :auto-upload="false" file-mediatype="all"
      @select="selectFile">
      <button size="mini" type="primary" class="mini-btn">上传文件</button>
    </uni-file-picker>
    <view class="uni-btn-v twoButton">
      <button ref="uploadRef" form-type="submit" type="warn" size="mini" @click="uploadVideoFile"
        :disabled="state.uploadButtonDisabled">提交</button>
    </view>

    <rich-text :nodes="question?.content" space="nbsp"></rich-text>>
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog cancelText="取消" confirmText="申请" message="您已上传视频" type="success" title="申请权限"
        content="您确定再上传一次吗？" :duration="2000" :before-close="true" @close="onClosePopup"
        @confirm="onConfirmPopup"></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="popupPlayVideo" type="dialog" background-color="#fff">
      <view>
        <video id="myVideo" :src="state.video_src" @error="videoErrorCallback" :danmu-list="danmuList" enable-danmu
          danmu-btn controls></video>
      </view>
      <view class="uni-list uni-common-mt">
        <view class="uni-list-cell">
          <view>
            <view class="uni-label">弹幕内容</view>
          </view>
          <view class="uni-list-cell-db">
            <input v-model="danmuValue" class="uni-input" type="text" placeholder="在此处输入弹幕内容" />
          </view>
        </view>
      </view>
      <view class="uni-btn-v">
        <button @click="sendDanmu" class="page-body-button">发送弹幕</button>
      </view>
    </uni-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import UniFilePicker from '@dcloudio/uni-ui/lib/uni-file-picker/uni-file-picker.vue'
import UniEasyinput from '@dcloudio/uni-ui/lib/uni-easyinput/uni-easyinput.vue'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import { getHasUploadVideoAPI, getQINIUTokenAPI } from '@/services/home'
import type { QuestionVideoPermitItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { domain_qiniu, qiniu_upload_url } from '@/utils/http'
import { useMemberStore } from '@/stores'

// 获取会员信息
let memberStore = reactive<any>({})
memberStore = useMemberStore()
// 通用性变量
const state = reactive({
  title: '',
  remark: '',
  type: 0,
  knowledgepoint: -1,
  file: '',
  open_level: 'public',
  bank_point: 2,
  key: '',
  token: '',
  uploadButtonDisabled: true,
  file_size: 0,
  video_src: '',
})
type danmuItem = {
  text: string
  color: string
  time: number
}
const popupPlayVideo = ref<any>()
const danmuList = ref<danmuItem[]>([])
const danmuValue = ref<string>('')
const videoContext = ref<any>()
const uploadRef = ref<any>()
const question = ref<QuestionVideoPermitItem>()
const tempFile = ref<any[]>([])
const hasUploadQuestionVideoList = ref<number[]>([])
// 选择框类型
type checkItem = {
  value: number
  text: string
  disable?: boolean
}
// 弹窗
const popup = ref()
// 弹窗关闭处理事件
const onClosePopup = () => {
  popup.value.close()
  uni.navigateTo({
    url: `step_one_upload_video`,
  })
}
// 发送弹幕
const sendDanmu = () => {
  videoContext.value.sendDanmu({
    text: danmuValue.value,
    color: getRandomColor(),
  })
  danmuValue.value = ''
}
//处理视频播放失败
const videoErrorCallback = (e: any) => {
  uni.showModal({
    content: e.target.errMsg,
    showCancel: false,
  })
}
// 弹幕字体随机颜色
const getRandomColor = () => {
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
// 弹窗确定事件, 申请录入试卷的权限，并刷新当前的试卷列表
const onConfirmPopup = () => {
  popup.value.close()
}

// 选择了正确格式的文件
const selectFile = (e: any) => {
  console.log('picker选择了视频', e)
  if (e.tempFilePaths.length > 0 && e.tempFiles[0].file.size <= 20 * 1024 * 1024) {
    state.file = e.tempFilePaths[0]
    state.file_size = e.tempFiles[0].file.size
    getToken()
  }
}
// 获取已经上传过的试题视频解析id列表，用于判断当前题目是否已经上传过，如果已经上传，提示是否确定修改
const getHasUploadVideoData = async () => {
  const res = await getHasUploadVideoAPI()
  console.log('已上传视频题目id列表：', res)
  if (res.code == 200) {
    hasUploadQuestionVideoList.value = res.data.results
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 获取七牛云的token
const getToken = async () => {
  const param_data = {
    key: state.key,
    suffix: 'mp4',
    file_size: state.file_size,
    question: question.value!.id,
  }
  const res = await getQINIUTokenAPI(param_data)
  console.log('token:', res)
  if (res.code == 200) {
    state.token = res.data.results
    state.uploadButtonDisabled = false
  } else {
    uni.showToast({ icon: 'success', title: '读取token失败' })
  }
}
// 页面加载
onLoad(async (opts: any) => {
  videoContext.value = uni.createVideoContext('myVideo')
  console.log('页面加载事件')
  getHasUploadVideoData()
  if (opts.question == undefined) {
    uni.showToast({ icon: 'error', title: 'no question' })
    // 停止页面加载动画
    setTimeout(() => {
      uni.navigateTo({
        url: `step_one_upload_video`,
      })
    }, 2000)
  }
  question.value = JSON.parse(decodeURIComponent(opts.question))
  console.log('第一步传来的question', question)
  if (hasUploadQuestionVideoList.value.includes(question.value!.id)) {
    popup.value.open()
  }
  let current_date = new Date()
  let date = current_date.getFullYear() + '-' + (current_date.getMonth() + 1).toString() + '-' + current_date.getDate()
  // let current_time = current_date.toLocaleTimeString()
  // state.key = question.value?.reference + question.value!.content_front.slice(0, 10) + date + '-' + randomNumber(5) + '.mp4'
  state.key = date + '-' + randomNumber(5) + '.mp4'
})
// 随机产生5个阿拉伯数字
const randomNumber = (len: number) => {
  let digit = Math.pow(len, 10)
  return Math.floor(Math.random() * 9 * digit + 10000).toString()
}
// 选择了文件, 成功后再提交表单
const uploadVideoFile = () => {
  uni.showLoading({ title: '正在上传ing', mask: true })
  let formData = {
    key: state.key,
    token: state.token,
    'x:question': question.value?.id,
    'x:owner': memberStore.profile.id,
  }
  // let keyName = 'x:question'
  // formData['x:question'] = question.value?.id
  console.log('要提交视频到七牛：', formData)
  uni.uploadFile({
    url: qiniu_upload_url,
    filePath: state.file,
    name: 'file',
    formData: formData, // HTTP 请求中其他额外的 form data
    success: (res: any) => {
      console.log('七牛云返回：', res)
      uni.hideLoading()
      if (res.statusCode == 200 || res.statusCode == 201 || res.statusCode == 202) {
        state.video_src = domain_qiniu + '/' + state.key
        popupPlayVideo.value.open()
      } else {
        uni.showToast({
          title: '上传失败！',
          icon: 'error',
          mask: true,
        })
      }
    },
    fail: (fail) => {
      console.log('七牛云上传失败！', fail)
      uni.hideLoading()
    },
  })
}

</script>
<style lang="scss" scoped>
.container {
  font-size: 30rpx;
  margin: 22rpx;
  padding: 5rpx;
}

.uni-input {
  border: 1rpx solid gray;
  border-radius: 20rpx;
}

.uni-form-item .title {
  padding: 10rpx 0;
}

.title {
  font-size: 30rpx;
  font-weight: bold;
  margin: 10rpx 0 5rpx 0;
}

.data-pickerview {
  height: 400px;
  border: 1px #e5e5e5 solid;
}

.popper__arrow {
  top: -6px;
  left: 50%;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #ebeef5;
}

.twoButton {
  padding: 10rpx;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
}
</style>
